package com.xuecheng.search.listener;

import com.xuecheng.search.service.SearchService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
/**
 * @Author 12441
 * @Date 2022/9/21 19:40
 * @Version 1.0
 */
@Component
@Slf4j
public class CoursePubListener {
    @Autowired
    private SearchService searchService;

    //MQ消息确定机制

    //监听课程发布的消息
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue("content.queue")
            , exchange = @Exchange(value = "content-exchange"
            , type = ExchangeTypes.TOPIC)
            , key = "course.pub"))
    public void listenCoursePubId(Long coursePubId) {
        log.info("监听课程发布的消息{}", coursePubId);
        // 课程同步
        try {
            searchService.CoursePubsyncToEs(coursePubId);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 下架监听
     * @param coursePubId
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue("content.queue2")
            , exchange = @Exchange(value = "content-exchange"
            , type = ExchangeTypes.TOPIC)
            , key = "course.down"))
    public void listenOfflineCourse(Long coursePubId) {
        log.info("监听课程下架的消息，课程ID:{}",coursePubId);
        // 同步索引库
        try {
            searchService.removeDocument(coursePubId);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
